//
//  LoginVC.swift
//  fir-mac
//
//  Created by dahua Liu on 2022/8/16.
//

import Cocoa
import KeychainAccess

class LoginVC: NSViewController {

    @IBOutlet weak var tokenTF: NSTextField!
    @IBOutlet weak var segment: NSSegmentedControl!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
    }
    
    @IBAction func sureClick(_ sender: NSButton) {
        let token = tokenTF.stringValue
        guard token.count > 0 else {
            let alert = NSAlert()
            alert.messageText = "错误"
            alert.informativeText = "api_token 不能为空！"
            alert.runModal()
            return
        }
        
        let isFir = segment.indexOfSelectedItem == 0
        HTTPManager.shared.APIToken = token
        HTTPManager.shared.isFirOrPGY = segment.indexOfSelectedItem == 0
        Keychain(service: KeychainFirmacServiceName)[KeychainFirmacAPITokenKey] = token
        Keychain(service: KeychainFirmacServiceName)[KeychainFirmacTokenType] = isFir ? TokenType.fir.rawValue : TokenType.pgy.rawValue
        NotificationCenter.default.post(name: Notification.Name.FIRLoginComplete, object: nil)
        self.dismiss(nil)
    }
    
    @IBAction func firTokenClick(_ sender: NSButton) {
        NSWorkspace.shared.open(URL(string: "https://fir.im/apps/apitoken")!)
    }
    
    @IBAction func pgyTokenClick(_ sender: NSButton) {
        NSWorkspace.shared.open(URL(string: "https://www.pgyer.com/account/api")!)
    }
    
    
}
